#include <windows.h>
#include <time.h>
#include "resource.h"

HINSTANCE ghInstance;

INT_PTR WINAPI OtherDialogProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	switch (msg)
	{
		case WM_CLOSE:
			DestroyWindow(hWnd);
			return TRUE;

		case WM_DESTROY:
			PostQuitMessage(0);
			return TRUE;

		case WM_COMMAND:
			switch (LOWORD(wParam))
			{
				case IDOK:
					MessageBox(0, "i am IDOK", 0, 0);
					return TRUE;

				case IDCANCEL:
					MessageBox(0, "i am IDCANCEL", 0, 0);
					return TRUE;
			}
			break;

		default:
			return FALSE;
	}
	return FALSE;
}

DWORD WINAPI thread_t1(void* para) {
	MSG msg;
	HANDLE hThread;
	HWND hDialog1 = CreateDialogParam(ghInstance, MAKEINTRESOURCE(RES_Dialog_t1), 0, OtherDialogProc, 0);
	if (hDialog1 == 0) {
		MessageBox(0, "create modeless dialog failure", 0, 0);
		return 0;
	}
	SetWindowText(hDialog1, para);
	ShowWindow(hDialog1, SW_SHOW);

	while (GetMessage(&msg, 0, 0, 0) > 0) {
		if (!IsDialogMessage(hDialog1, &msg)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}
	return 0;
}

INT_PTR WINAPI MainDialogProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
	switch (msg)
	{
		case WM_CLOSE:
			DestroyWindow(hWnd);
			return TRUE;

		case WM_DESTROY:
			PostQuitMessage(0);
			return TRUE;

		case WM_COMMAND:
			switch (LOWORD(wParam))
			{
				case IDOK:
					{
						HANDLE hThread;
						static char buf[16];
						sprintf(buf, "rand: %d", rand() % 100);

						hThread = _beginthreadex(0, 0, thread_t1, buf, 0, 0);
						if (hThread != 0) {
							CloseHandle(hThread);
						} else {
							MessageBox(0, "create thread failure", 0, 0);
						}
					}
					return TRUE;

				case IDCANCEL:
					return TRUE;
			}
			break;

		default:
			return FALSE;
	}
	return FALSE;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	HWND hMainDialog, hOtherDialog, hDialogList[2];
	MSG msg;
	BOOL bReturn;

	ghInstance = hInstance;
	srand(time(0));

	hMainDialog = CreateDialogParam(hInstance, MAKEINTRESOURCE(RES_Dialog_t1), 0, MainDialogProc, 0);
	if (hMainDialog == 0) {
		MessageBox(0, "create modeless dialog failure", 0, 0);
		return 0;
	}
	SetWindowText(hMainDialog, "Main Dialog");
	ShowWindow(hMainDialog, SW_SHOW);

	hOtherDialog = CreateDialogParam(hInstance, MAKEINTRESOURCE(RES_Dialog_t1), 0, MainDialogProc, 0);
	if (hOtherDialog == 0) {
		MessageBox(0, "create modeless dialog failure", 0, 0);
		return 0;
	}

	SetWindowText(hOtherDialog, "Other Dialog");
	ShowWindow(hOtherDialog, SW_SHOW);

	hDialogList[0] = hMainDialog, hDialogList[1] = hOtherDialog;

	while (GetMessage(&msg, 0, 0, 0) > 0) {
		int i;
		for (i = 0; i < 2; ++i) {
			if (!IsDialogMessage(hDialogList[i], &msg)) {
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
	}
	MessageBox(0, 0, 0, 0);
	return 0;
}
